package com.nmcc.app_adherence;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.SystemClock;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.InputType;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class AdherenceActivity extends Activity {
	private static int attempsdeletedatabase=0;
	
	private static String startcounterAs1StopAs2="1";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_adherence);
		
		//updateStartStopCounter("1");
		startcounterAs1StopAs2="1";
		
		Toast.makeText(getApplicationContext(), "Please run ODK Survey at least once if there is an error when merging files. Besides, merging errors can also image if some tables are missing in ODK Survey.", Toast.LENGTH_LONG).show();
		boolean d=CheckIfFirstTimeUseOfODKSsurveyWasDone();
		
		//Toast.makeText(getApplicationContext(), String.valueOf(d), Toast.LENGTH_LONG).show();
		
        Button b2 = (Button) findViewById(R.id.btnOdksurveyAdherence);
        b2.setOnClickListener(new View.OnClickListener() {
           public void onClick(View arg0) {
        	   //updateStartStopCounter("2");

        	   startcounterAs1StopAs2="2";
        	   
        	   //launchOdkSurvey(arg0);
        	   //Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
        	   Toast.makeText(getApplicationContext(), "Reminder: This phone shall ONLY contain ADHERENCE forms in ODK Survey.", 5000).show();
        	   Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("org.opendatakit.survey.android");
        	   startActivity(LaunchIntent);
        	   
        	   ReconcileODKAndCSVCompletedHouses(arg0);
        	   
           }
        });  
        
        
		 Button btnClearBluetoothfolder = (Button) findViewById(R.id.btnClearBluetoothFolder);
	        btnClearBluetoothfolder.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	   startcounterAs1StopAs2="1";
	        	   
	        	   ClearBluetoothFolderVerifier(arg0);
	           }
	        });	
	        
	     //
	        Button btnBluetoothCount = (Button) findViewById(R.id.btnCountFilesInBluetoothFolder);
	        btnBluetoothCount.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	
	        	   CountGPSDataFilesInBluetoothFolder();
	           }
	        });		        
	        
	        
	        
	        
	        //btnOtherTasks
	        Button btnOtherTasks = (Button) findViewById(R.id.btnOtherTasks);
	        btnOtherTasks.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {

	        	   Intent i = new Intent(AdherenceActivity.this, OtherTasks.class);
	               startActivity(i);
	           }
	        });
	        
		      //btnClearAllTables
	        Button btnClearAllTables = (Button) findViewById(R.id.btnClearDatabase);
	        btnClearAllTables.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	   //add within scope of 3 seconds
	        	   
	        	   ClearDatabasesLinker(arg0);
	
	        	   
	           }
	        });
	        
	        //btnPutMergedFileIntoODK
	        Button btnSendmergeCSVToOdk = (Button) findViewById(R.id.btnPutMergedFileIntoODK);
	        btnSendmergeCSVToOdk.setOnClickListener(new View.OnClickListener() {
	           public void onClick(View arg0) {
	        	   //SendMergedCSVToODK(arg0);
	        	   MergeCSVPreLinker(arg0);
	        	   
	           }
	        }); 
		
	       // ActionStartsHere();
	}

	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.adherence, menu);
		return true;
	}

	
	public void rebootphone()
    {
    	try{
    		//Runtime.getRuntime().exec("su");
    		
    		Runtime.getRuntime().exec(new String[]{"su", "-c", "reboot now"});
    		
    	} catch(IOException e){
    		
    	}
	
    }
	
	public void ClearBluetoothFolderVerifier(final View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to clear the bluetooth folder?")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
		        	   
		        	   ClearBluetoothFolderLinker(view);	   
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                // some code if you want
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();

		
	}
	
	public void ClearDatabasesLinker(View view){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to clear the database? You will lose all the data. New tables will be copied to ODK Survey.")
		       .setCancelable(false)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
		        	   
		        	   attempsdeletedatabase= attempsdeletedatabase + 1;

		        	   if (attempsdeletedatabase==2){

		        			  Toast.makeText(getApplicationContext(), "Warning! All data in ODK Survey tables will be cleared.", Toast.LENGTH_LONG).show();
		     				 //all contents of the meta data folder
		     				
		     				  Toast.makeText(getApplicationContext(), "After reboot, run Treatment Adherence in GPS2_A to complete process.", Toast.LENGTH_LONG).show();

		        		   
		        		   ClearDatabaseGivePassword();
		        		   
		        		   attempsdeletedatabase=0;
		        	   }
		        	   
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                // some code if you want
		                dialog.cancel();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();

		
	}
	
	public void ClearDatabaseGivePassword(){
		AlertDialog.Builder alert = new AlertDialog.Builder(this);

		alert.setTitle("Clear Databases");
		alert.setMessage("Password");

		
		// Set an EditText view to get user input 
		final EditText input = new EditText(this);
		alert.setView(input);
		input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
		
		alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
		  String value = input.getText().toString();
		  // Do something with value!
		  if (value.equals("path14$")){

  
		       	   ClearAllTablesEmptyDatabase();
		       	   RebootPhoneAndClearODKTables();
		       	   
		       	   
		      // UpdatePhoneNameLinker();
		  }
		  
		  
		  }
		});

		alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		  public void onClick(DialogInterface dialog, int whichButton) {
		    // Canceled.
		  }
		});

		alert.show();
	}
	
	public void ClearBluetoothFolderLinker(View view){
 		final Context context = this;
	  MergeCSV merg = new MergeCSV();

merg.DeleteAllFilesInBluetoothFolder(view);//gps house merge

Toast.makeText(context, "The bluetooth folder has been cleared, now ready to receive today's csv files from various phones.", Toast.LENGTH_LONG).show();
// Files: Input
}    

	
public void ClearAllTablesEmptyDatabase(){
		   MySQLiteHelper db = new MySQLiteHelper(this);
		   //to avoid overwriting in odk survey just send to sd card folder
	    // add Books
	    //db.DropAllTables();
		  Toast.makeText(getApplicationContext(), "Warning! This will clear all the data in the database.", 5000).show();
	  
	  db.DropAllTables();
	   
	 Toast.makeText(getApplicationContext(), "Database cleared. This is usefull when migrating to an updated version only.", 5000).show();

	}
	



public void CountGPSDataFilesInBluetoothFolder(){
   	//copy csv files into a e.g 3-3-2014 folder
   	File sdcard = Environment.getExternalStorageDirectory();

   		//String csvFile;
   		int numFiles=300;
   		String CSVfilenameGPS;
   		String CSVfilenamePersons;
   		int person=0;
   		int gpsdat=0;
   		
           // Files: Input
           for (int i = 0; i <= numFiles; i++) {
           	
           	if (i==0) {//only at first time also get GPSData.csv or Persons.csv since first phone sends this file
           		CSVfilenameGPS="GPSData.csv";
           		CSVfilenamePersons="Persons.csv";
		    	 }
		    	 else{
		    		 CSVfilenameGPS="GPSData_" + i + ".csv";
		    		 CSVfilenamePersons="Persons_" + i + ".csv";
		    	 }
           	
           	//number 1 either gpsdata or persons do together for num N
           	//Do for GPSData
           	//String CSVfilenameGPS="GPSData(" + i + ").csv";
           	File fSource=new File(sdcard+ "/bluetooth/" + CSVfilenameGPS);
           	//check if file exists
               	 boolean alreadyExists = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + CSVfilenameGPS).exists();
  	          
               	 if (alreadyExists) {
               		 	
                		gpsdat = gpsdat + 1;
               	 }
               	 else{
  	        	  		//do nothing
               	 }
               //end of gpsdata copying
               	 
               //Do for Persons file
                   //String CSVfilenamePersons="Persons(" + i + ").csv";
                   File fSourcePersons=new File(sdcard+ "/bluetooth/" + CSVfilenamePersons);
                   //check if file exists
	                boolean alreadyExistsPersons = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + CSVfilenamePersons).exists();
          	          
	                if (alreadyExistsPersons) {
	                	//boolean deleted = fSourcePersons.delete();
	                	person = person + 1;
	                }
	                   else{
          	        	 //do nothing
	                }
	            //end of persons data copying
	                
	                TextView myinfo = (TextView) findViewById(R.id.lblinfo);
	         	   myinfo.setText("You currently have " + gpsdat + " GPSData file(s) and " + person + " Persons file(s) in your bluetooth folder.");
           }
   	
   }
	

public void LinkerCopyMergedCSVMasterToODK(View view){

    // }
	 
	  MergeCSV merg = new MergeCSV();
   //to avoid overwriting in odk survey just send to sd card folder
   // add Books
   //db.DropAllTables();
	MergeMultipleCSV(view);
	
 merg.CopyMergedMasterFileToODKSurvey(view);//launchProcedure(this, 1);//gps house merge send to odk


}


public void MergeCSVPreLinker(final View view){
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	builder.setMessage("You are about to Merge your current files to ODK for Adherence Follow up, are you sure you want to proceed?")
	       .setCancelable(false)
	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	                //MyActivity.this.finish(); //Close  this Activity for example: MyActivity.java
	        	   
	        	   LinkerCopyMergedCSVMasterToODK(view);	   
	           }
	       })
	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	                // some code if you want
	                dialog.cancel();
	           }
	       });
	AlertDialog alert = builder.create();
	alert.show();

	
}



public void MergeMultipleCSV(View view){
	
  	//**********************
  	//*****
  	CreateTodayFolderCopyCSVFiles(view);
  	//**********************
  	//**********************
  	//now do merging
  	Toast.makeText(getApplicationContext(), "Please make sure that you put csv files into the bluetooth folder, sending from various phones.", Toast.LENGTH_LONG).show();
        
  	  MergeCSV merg = new MergeCSV();
	   //to avoid overwriting in odk survey just send to sd card folder
      // add Books
      //db.DropAllTables();
    merg.launchProcedure(this, 2);//gps house merge
    merg.launchProcedure(this, 4);//persons
     //db.getGPSRecordsCount();
    	//now take to odk
  }


public void CreateTodayFolderCopyCSVFiles(View view){
	//copy csv files into a e.g 3-3-2014 folder
	File sdcard = Environment.getExternalStorageDirectory();
	   
	   
	   Calendar c = Calendar.getInstance();
	   int day = c.get(Calendar.DAY_OF_MONTH);
		   int year = c.get(Calendar.YEAR);
		   int currentmonth = c.get(Calendar.MONTH);
		   String newFileName = day + "-" + currentmonth + "-" + year + "-GPS";
		   
	CreateFolderInSdCard(view,"/bluetooth/" + newFileName );
	
	
	
	try
 	{
		//String csvFile;
		int numFiles=300;
		String CSVfilenameGPS;
		String CSVfilenamePersons;
		//first copy GPSData.csv and Persons.csv files from first phone
		

		
        // Files: Input
        for (int i = 0; i <= numFiles; i++) {
        	
        	if (i==0) {//only at first time also get GPSData.csv or Persons.csv since first phone sends this file
        		CSVfilenameGPS="GPSData.csv";
        		CSVfilenamePersons="Persons.csv";
	    	 }
	    	 else{
	    		 CSVfilenameGPS="GPSData_" + i + ".csv";
	    		 CSVfilenamePersons="Persons_" + i + ".csv";
	    	 }
        	
        	
        	//number 1 either gpsdata or persons do together for num N
        	//Do for GPSData
        	//String CSVfilenameGPS="GPSData(" + i + ").csv";
        	File fSource=new File(sdcard+ "/bluetooth/" + CSVfilenameGPS);
        	File fDestin=new File(sdcard + "/bluetooth/" + newFileName + "/" + CSVfilenameGPS);
        	//check if file exists
            	 boolean alreadyExists = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + CSVfilenameGPS).exists();
	          
            	 if (alreadyExists) {
            		 	copyFileUsingFileChannels(fSource,fDestin);
            	 }
            	 else{
	        	  		//do nothing
            	 }
            //end of gpsdata copying
            	 
            //Do for Persons file
                //String CSVfilenamePersons="Persons(" + i + ").csv";
                File fSourcePersons=new File(sdcard+ "/bluetooth/" + CSVfilenamePersons);
                File fDestinPersons=new File(sdcard + "/bluetooth/" + newFileName + "/" + CSVfilenamePersons);
                //check if file exists
                boolean alreadyExistsPersons = new File(Environment.getExternalStorageDirectory().toString() + "/bluetooth/" + CSVfilenamePersons).exists();
       	          
                if (alreadyExistsPersons) {
                    	copyFileUsingFileChannels(fSourcePersons,fDestinPersons);
                }
                   else{
       	        	 //do nothing
                }
            //end of persons data copying
            	 
        }
		
		
 	}
 	catch(IOException e)
 	{
 	     e.printStackTrace();
 	} 
	
}


private static void copyFileUsingFileChannels(File source, File dest)
        throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(dest).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}


public void CreateFolderInSdCard(View view, String foldername){
	
	File sdcard = Environment.getExternalStorageDirectory();
	File f=new File(sdcard+"/" + foldername);
	f.mkdir();
	
 Toast.makeText(getApplicationContext(), "Today's bluetooth receiving Folder created", 5000).show();

} 

public void updateStartStopCounter(String startcounterAs1StopAs2){
	MySQLiteHelper db = new MySQLiteHelper(this);
	
	db.addSetting(0, 0, "","",startcounterAs1StopAs2);
	   
    
}


		public void RebootPhoneAndClearODKTables(){
		
			  File sdcard = Environment.getExternalStorageDirectory();
			//the metadata
			  File f1=new File(sdcard+"/opendatakit/survey/metadata/appCache");
				File f2=new File(sdcard+"/opendatakit/survey/metadata/geoCache");
				File f3=new File(sdcard+"/opendatakit/survey/metadata/webDb");
				//leave out the survey.properties for now
	
				
			  deleteDir(f1);
			  deleteDir(f2);
			  deleteDir(f3);

			  //now clear tables of odk folder
			  
			  //File f4=new File(sdcard+"/opendatakit/survey/assets");
				//File f5=new File(sdcard+"/opendatakit/survey/framework");
				//File f6=new File(sdcard+"/opendatakit/survey/output");
				File f7=new File(sdcard+"/opendatakit/survey/tables");

			  //deleteDir(f4);
			 // deleteDir(f5);
			 // deleteDir(f6);
			  deleteDir(f7);
		  
	  
			  //now copy contents of assets into the tables folder in odk survey
			 // File assetsfolder =Context.getAssets();// getAssets().toString();

			  
			  
			  //File sourcef4=new File(getAssets().toString()+"/assets");
				//File sourcef5=new File(getAssets().toString()+"/framework");
				//File sourcef6=new File(getAssets().toString()+"/output");
			    File sourcef8=new File(getAssets().toString()+"/username");
				File sourcef7=new File(getAssets().toString()+"/tables");
				
				  //File destinf4=new File(sdcard+"/opendatakit/survey/assets");
					//File destinf5=new File(sdcard+"/opendatakit/survey/framework");
					//File destinf6=new File(sdcard+"/opendatakit/survey/output");
				File destinf8=new File(sdcard+"/opendatakit/username");
					File destinf7=new File(sdcard+"/opendatakit/survey/tables");		
				
					  Toast.makeText(getApplicationContext(), getAssets().toString(), 5000).show();


					  //copyAssetFolder(getAssets(), "assets", 
							 // destinf4.toString());
					  
					 // copyAssetFolder(getAssets(), "framework", 
							  //destinf5.toString());
					  
					  //copyAssetFolder(getAssets(), "output", 
							 // destinf6.toString());
					  
					  copyAssetFolder(getAssets(), "tables", 
							  destinf7.toString());
					
					  copyAssetFolder(getAssets(), "username", 
							  destinf8.toString());
					  
					//try
					//{
						//copyFileUsingFileChannels(sourcef4,destinf4);
						//copyFileUsingFileChannels(sourcef5,destinf5);
						//copyFileUsingFileChannels(sourcef6,destinf6);
						//copyFileUsingFileChannels(sourcef7,destinf7);
					//}
				 	//catch(IOException e)
				 	//{
				 	     //e.printStackTrace();
				 	//} 
								//now copy from assets folder
			
			 // delaycode();
			  //restart phone;
       	   rebootphone();

       	// Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("org.opendatakit.survey.android");
  	   //startActivity(LaunchIntent);
		}

		
		public void delaycode(){
			try{
				Thread.sleep(5000);
			} catch (InterruptedException e){
				e.printStackTrace();
			}
		}
		public static boolean deleteDir(File dir) {
		    if (dir.isDirectory()) {
		        String[] children = dir.list();
		        for (int i=0; i<children.length; i++) {
		            boolean success = deleteDir(new File(dir, children[i]));
		            if (!success) {
		                return false;
		            }
		        }
		    }

		    // The directory is now empty so delete it
		    return dir.delete();
		}
		
		
		private static boolean copyAssetFolder(AssetManager assetManager,
	            String fromAssetPath, String toPath) {
	        try {
	            String[] files = assetManager.list(fromAssetPath);
	            new File(toPath).mkdirs();
	            boolean res = true;
	            for (String file : files)
	                if (file.contains("."))
	                    res &= copyAsset(assetManager, 
	                            fromAssetPath + "/" + file,
	                            toPath + "/" + file);
	                else 
	                    res &= copyAssetFolder(assetManager, 
	                            fromAssetPath + "/" + file,
	                            toPath + "/" + file);
	            return res;
	        } catch (Exception e) {
	            e.printStackTrace();
	            return false;
	        }
	    }
	
		
		private static boolean copyAsset(AssetManager assetManager,
	            String fromAssetPath, String toPath) {
	        InputStream in = null;
	        OutputStream out = null;
	        try {
	          in = assetManager.open(fromAssetPath);
	          new File(toPath).createNewFile();
	          out = new FileOutputStream(toPath);
	          copyFile(in, out);
	          in.close();
	          in = null;
	          out.flush();
	          out.close();
	          out = null;
	          return true;
	        } catch(Exception e) {
	            e.printStackTrace();
	            return false;
	        }
	    }

	    private static void copyFile(InputStream in, OutputStream out) throws IOException {
	        byte[] buffer = new byte[1024];
	        int read;
	        while((read = in.read(buffer)) != -1){
	          out.write(buffer, 0, read);
	        }
	    }

	//}
	    
	
		   public void ReconcileODKAndCSVCompletedHouses(View view) {
			   SQLiteDatabase db;
				
			   String dir = Environment.getExternalStorageDirectory().getPath();
				File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
				db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
			   
			  // spnNotCompletedAdherenceHouses = (Spinner) findViewById(R.id.spnHousesNotCompletedByTestingPair);
		    	//lstvwHouseList=(ListView) findViewById(R.id.houses_listview);
		      List list = new ArrayList();
		      //add all the house get name personid
		      //for loop
		      
		      String houseid;
		      
		      int numrecs=0;
				    Cursor cursor = db.rawQuery("SELECT * FROM household2 where hvist_result='_1'", null);
				    if (cursor.moveToFirst())
				    {
				        do
				        {
				        	 //list.add(cursor.getString(14) + " - " + cursor.getString(11));

				        	     houseid = cursor.getString(14);
				        	 
				        	     db.execSQL("UPDATE gpsdata SET " +
				        		      		"DueForFollowUp=0 WHERE household_id='" + houseid + "'");

				        } while(cursor.moveToNext());
				    }

				    db.close();  
			    	     
			  //creategpsdataTableInODK();
			   
			  //ExportGPSDataTakeToODKDirectNewMethod(view, 1, "no comment", "placename", "newhouseguid" );
			  // List list = new ArrayList();
			      //add all the house get name personid
			      //for loop
			   //String household_id_got="kkkkk";
			   
			      //int numrecs=0;
					 //   Cursor cursor = db.rawQuery("SELECT * FROM household2 where hvisit_result='_1'", null);
					   // if (cursor.moveToFirst())
					   // {
					       // do
					       // {
					        	 //list.add(cursor.getString(17) + " - " + cursor.getString(11));
					        	// numrecs=numrecs+1;
					        	 //get householdid
					        	// household_id_got=cursor.getString(17);
					        	 
					        	// ContentValues cv = new ContentValues();
		  			        	//  cv.put("HHResult", "_1");
					        	// String dataToInsert
					        	// String where = "id='?'";
					        	 //String[] whereArgs= new String[] {household_id_got};
					        	 
					        	// db.update("gpsdata",  cv, where,  whereArgs);
					        	 
					     	   //Toast.makeText(getApplicationContext(), "nnnnnnnn", 5000).show();
					     	   
					        	 
					        //} while(cursor.moveToNext());
					        
					      
					        
					   // }
					    	//db.close();
			  
			  
		   }	
  		 
		   public void UpdatePhoneNameLinker(){
			  final MySQLiteHelper db = new MySQLiteHelper(this);
			   //final boolean result;
			   
				AlertDialog.Builder alert = new AlertDialog.Builder(this);

				alert.setTitle("Update Phone Name: Currently " + db.GetSettingDeviceName());
				alert.setMessage("Phone Name");
                    
				
				// Set an EditText view to get user input 
				final EditText input = new EditText(this);
				alert.setView(input);
				input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				
				alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
				  String value = input.getText().toString();
				  // Do something with value!
				  if (!value.equals("")){
		  
					  db.UpdateDeviceName(value);
				  
				  }
				  
				  
				  }
				});

				alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
				  public void onClick(DialogInterface dialog, int whichButton) {
				    // Canceled.
				  }
				});

				alert.show();
			
		   }
			
		   
		   public boolean CheckIfFirstTimeUseOfODKSsurveyWasDone() {
			   SQLiteDatabase db;
				boolean tableexists=false;
			   String dir = Environment.getExternalStorageDirectory().getPath();
				File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
				
				boolean alreadyExistsODKDatabase = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db").exists();
				boolean odksurveywasopened=false;
				
				if (!alreadyExistsODKDatabase){
					odksurveywasopened=true;
					Toast.makeText(getApplicationContext(),"Open Monitoring and Adherence forms once , then close both forms without entering anything to activate ODK Survey.", Toast.LENGTH_LONG).show();

					//start odk survey to create the database
					  Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("org.opendatakit.survey.android");
		        	   startActivity(LaunchIntent);
		        	  return false;
				}
				
				//now it exists
				db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);

				List list = new ArrayList();
		      //add all the house get name personid
		      //for loop
               //try again if database now exists
				//boolean AgainCheckIfalreadyExistsODKDatabase1 = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db").exists();
				
				//if (AgainCheckIfalreadyExistsODKDatabase1){
					
				     int numrecs=0;
						   // Cursor cursor = db.rawQuery("SELECT * FROM household2", null);
				     		Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='household2'", null);
						    if (cursor.moveToFirst())
						    {
						       // do
						        //{
						        	tableexists=true;

						       // } while(cursor.moveToNext());
						    }

						    db.close();  
						    
						    //Toast.makeText(getApplicationContext(),hasatleastonerecord, 5000).show();
							 if (!tableexists){
								if (!odksurveywasopened){
									Toast.makeText(getApplicationContext(),"Open Monitoring and Adherence forms at least once and then close the forms without entering anything to activate ODK Survey.", Toast.LENGTH_LONG).show();

									//start odk survey to create the database
									  Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("org.opendatakit.survey.android");
						        	   startActivity(LaunchIntent);

								}
							 }
						    

				//}
				
				    return tableexists;
			   
		   }	
  		 

		
}
